/*
 * FindBugs - Find Bugs in Java programs
 * Copyright (C) 2003-2008 University of Maryland
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.umd.cs.findbugs.gui2.sort;

import java.util.Arrays;
import java.util.Comparator;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.gui2.BugLeafNode;
import edu.umd.cs.findbugs.gui2.BugSet;
import edu.umd.cs.findbugs.gui2.MainFrame;
import edu.umd.cs.findbugs.gui2.BugAspects.SortableValue;

/**
 * @author Graham Allan (grallan@cis.strath.ac.uk)
 */
public abstract class AbstractSortable implements Sortable {

	private String prettyName;

	public AbstractSortable(String prettyName) {
		this.prettyName = prettyName;
	}

	@Override
	public String toString() {
		return prettyName;
	}

	public abstract String getFrom(BugInstance bug);

	public String[] getAll() {
		return getAll(BugSet.getMainBugSet());
	}

	public String[] getAll(BugSet set) {
		return set.getAll(this);
	}

	public String formatValue(String value) {
		return value;
	}

	public int compare(SortableValue one, SortableValue two) {
		// Lexicographical by default
		return one.value.compareTo(two.value);
	}

	public String[] getAllSorted() {
		return getAllSorted(BugSet.getMainBugSet());
	}

	public String[] getAllSorted(BugSet set) {
		String[] values = getAll(set);
		SortableValue[] pairs = new SortableValue[values.length];
		for (int i = 0; i < values.length; i++)
			pairs[i] = new SortableValue(this, values[i]);
		Arrays.sort(pairs, this);
		for (int i = 0; i < values.length; i++)
			values[i] = pairs[i].value;
		return values;
	}

	private SortableStringComparator comparator = new SortableStringComparator(this);

	public SortableStringComparator getComparator() {
		return comparator;
	}

	public Comparator<BugLeafNode> getBugLeafNodeComparator() {
		final Sortable key = this;
		return new Comparator<BugLeafNode>() {
			public int compare(BugLeafNode one, BugLeafNode two) {
				return key.compare(new SortableValue(key, key.getFrom(one.getBug())), new SortableValue(key, key
						.getFrom(two.getBug())));
			}
		};
	}

	public boolean isAvailable(MainFrame frame) {
		return true;
	}

	public String prettyName(){
		return prettyName;
	}
	
}
